package com.yn.pet.web.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yn.pet.bus.model.BaseStation;
import com.yn.pet.bus.model.WifiInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: WeatherUtil
 * @Description: 获取天气数据
 * @Author: lml
 * @Date: 2025/2/19 14:59
 **/
@Slf4j
public class LocationUtil {
    private static final String API_KEY = "1c65f7cd9dfe0006dd428df051564764";

    private static final String TX_API_KEY = "OK5BZ-RKQCG-63MQB-Q4SBR-IWCHH-OXFL4";

    public static String getLocation(String latitude, String longitude) {
        try {

            //接口参数getTDThttps://union.hnynsoft.com/iwatchhttps://api.tianditu.gov.cn/geocoderpostStr={"lon":"113.66962392744809","lat":"34.68763495041662","ver":1}&type=geocode&tk=047a37bbe69c5b7627757c8b75dcbe54"" token=
            String url = String.format(
                    "http://api.tianditu.gov.cn/geocoder?postStr={'lon':%s,'lat':%s,'ver':1}&type=geocode&tk=%s", longitude,
                    latitude, API_KEY);
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            JSONObject jsonResponse = JSON.parseObject(response.toString());
            log.info("{}", jsonResponse);
            //            String city = jsonResponse.getJSONObject("result").getJSONObject("addressComponent").getString("city");
            return jsonResponse.getJSONObject("result").getString("formatted_address");
        } catch (Exception e) {
            log.error("获取位置信息：{}", e.getMessage(), e);
            return "";
        }
    }

    public static Tuple2<Double, Double> getLocationByTX(String imei, List<BaseStation> baseStationList, List<WifiInfo> wifiInfoList) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("key", TX_API_KEY);
        requestBody.put("device_id", imei);

        if (!CollectionUtils.isEmpty(wifiInfoList)) {
            List<Map<String, Object>> wifiinfos = new ArrayList<>();
            for (WifiInfo wifiInfo : wifiInfoList) {
                Map<String, Object> wifiinfo = new HashMap<>();
                wifiinfo.put("mac", wifiInfo.getMac());
                wifiinfo.put("rssi", wifiInfo.getRss());
                wifiinfos.add(wifiinfo);
            }
            requestBody.put("wifiinfo", wifiinfos);
        } else if (!CollectionUtils.isEmpty(baseStationList)) {
            List<Map<String, Object>> cellinfos = new ArrayList<>();
            for (BaseStation baseStation : baseStationList) {

                Map<String, Object> cellinfo = new HashMap<>();
                cellinfo.put("mcc", baseStation.getMcc());
                cellinfo.put("mnc", baseStation.getMnc());
                cellinfo.put("lac", baseStation.getLac());
                cellinfo.put("cellid", baseStation.getCellid());
                cellinfo.put("rss", baseStation.getRss());
                cellinfos.add(cellinfo);
            }
            requestBody.put("cellinfo", cellinfos);
        } else {
            log.error("获取位置信息：{}", "参数为空");
            return null;
        }


        String jsonString = JSON.toJSONString(requestBody);
        System.out.println(jsonString);

        String url = "https://apis.map.qq.com/ws/location/v1/network";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        String body = response.getBody();
        JSONObject bodyJsonObject = JSON.parseObject(body, JSONObject.class);
        Object status = bodyJsonObject.get("status");
        if (status != null && status.toString().equals("0")) {
            JSONObject resultJsonObject = bodyJsonObject.getJSONObject("result");

            JSONObject locationJsonObject = resultJsonObject.getJSONObject("location");
            if (locationJsonObject != null) {
                String latitude = locationJsonObject.getString("latitude");
                String longitude = locationJsonObject.getString("longitude");
                return Tuples.of(Double.parseDouble(latitude), Double.parseDouble(longitude));
            }

        }
        return null;
    }


}
